<script lang='ts' setup>
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router'
import RoleApi from '/@/api/org/bean/role'
import managerServiceApi from '/@/api/org/bean/manger'
import RoleForm from './component/role-form.vue';
import { jumpPath, redirectPath } from '/@/utils/router-kit';
import { RoleEditUrl, RoleIndexUrl } from '/@/views/org/mapping.json'
import RoleUnitUserList from '../role-unit-user/component/role-unit-user-list.vue'
import menuTree from '../app-menu/component/app-menu-tree.vue'
import { ElNotification } from 'element-plus';
const router = useRouter();
//表单子组件的ref
const RoleFormRef = ref();
// 菜单树
const MenuTreeRef = ref();
// 菜单树（分配）
const MenuTreeDistributeRef = ref();
const url = RoleIndexUrl;
//当前页面state
const RoleFormState = reactive({
    loading: false,
    roleId: router.currentRoute.value.params.id as string,
    getRoleFormData: () => RoleFormRef.value.getRoleFormData(),

    // 保存按钮点击事件
    onSaveButtonClick: () => {
        RoleFormState.loading = true
        let master = RoleFormState.getRoleFormData()
        let detail: any[] = []
        // 菜单权限选中节点数据处理
        MenuTreeRef.value.getCheckedNodes().forEach((item: { attributes: { menuCode: any; }; }) => {
            let element = {
                resourceId: item.attributes.menuCode,
                resourceOpt: 1,
                resourceType: "MENU",
                roleId: RoleFormState.roleId
            }
            detail.push(element)
        });
        // 菜单权限(分配)选中节点数据处理
        // 管理类型角色才有分配菜单的权限
        if (RoleFormState.distributeCardVisible) {
            MenuTreeDistributeRef.value.getCheckedNodes().forEach((item: { attributes: { menuCode: any; }; }) => {
                let element = {
                    resourceId: item.attributes.menuCode,
                    resourceOpt: 2,
                    resourceType: "MENU",
                    roleId: RoleFormState.roleId
                }
                detail.push(element)
            });
        }

        if (master.roleType != 1) {
            // 非管理角色
            master.adminRange = null
        }

        RoleApi.saveMasterDetail(master, { insert: detail }, "update").then(res => {
            RoleFormState.loading = false
            ElNotification({ type: 'success', message: "保存成功" })
            redirectPath(RoleEditUrl + RoleFormState.roleId)
        }).finally(() => {
            RoleFormState.loading = false
        })
    },
    // 返回按钮点击事件
    onBackButtonClick: () => {
        jumpPath(RoleIndexUrl)
    },
    // 新增成功回调函数
    onAddFormSuccess: (formData: any) => {
        redirectPath(RoleEditUrl + formData.userId)
    },

    // 菜单权限（分配）是否显示
    distributeCardVisible: false,
    changeRoleType: (val: any) => {
        if (val == 1) {
            RoleFormState.distributeCardVisible = true
        } else {
            RoleFormState.distributeCardVisible = false
        }
    },

    ///// 树数据加载 start //////
    // 树节点数据
    treeData: [] as any[],
    // 已选择的树节点key 菜单权限
    setTreeKeys: [] as any[],
    // 已选择的树节点key 菜单权限（分配）
    setTreeDistributeKeys: [] as any[],
    // 加载树节点数据处理函数
    loadMenuTreeData: () => {
        managerServiceApi.getAdminResourceForRole("MENU", RoleFormState.roleId, RoleFormState.getRoleFormData().appId).then(res => {
            const treeNodeArr = res.data
            treeNodeArr.forEach((item: any) => RoleFormState.handleTreeData(item, res.data))
            RoleFormState.treeData = treeNodeArr
        })
    },
    // 处理树形数据，找已被勾选的
    handleTreeData: (parentMneu: any, resourceData: any[]) => {
        if (parentMneu.attributes.checked) {
            RoleFormState.setTreeKeys.push(parentMneu.id)
        }
        if (parentMneu.attributes.adminChecked) {
            RoleFormState.setTreeDistributeKeys.push(parentMneu.id)
        }
        resourceData.forEach(item => {
            item.menuName = item.text
            item.menuId = item.id
            RoleFormState.handleTreeData(item, item.children)
        })
    }
    ///// 树数据加载 end //////

})

onMounted(() => {
    RoleFormState.loadMenuTreeData()
    MenuTreeRef.value.setCheckedKeys(RoleFormState.setTreeKeys)
    MenuTreeDistributeRef.value.setCheckedKeys(RoleFormState.setTreeDistributeKeys)
})
</script>

<template>
    <jxtech-basic-header :breadcrumb-mapping-url="url">
        <template #extra>
            <jxtech-save-button @click="RoleFormState.onSaveButtonClick"></jxtech-save-button>
            <jxtech-back-button @click="RoleFormState.onBackButtonClick"></jxtech-back-button>
        </template>
    </jxtech-basic-header>

    <div v-loading="RoleFormState.loading" element-loading-text="正在更新...">
        <el-card>
            <template #header>
                <div class="jxtech-card-title">
                    <span>角色与权限</span>
                </div>
            </template>
            <role-form
                ref="RoleFormRef"
                :role-id="RoleFormState.roleId"
                @add-success="RoleFormState.onAddFormSuccess"
                @change-role-type="RoleFormState.changeRoleType"
            ></role-form>
        </el-card>
        <div>
            <role-unit-user-list class="mt10" :role-id="RoleFormState.roleId"></role-unit-user-list>
            <el-card class="mt10">
                <template #header>
                    <div class="jxtech-card-title">
                        <span class="jxtech-page-table-header-flex-title">菜单权限</span>
                    </div>
                </template>
                <menu-tree
                    ref="MenuTreeRef"
                    :show-checkbox="true"
                    :is-custom-tree-data="true"
                    :custom-tree-data="RoleFormState.treeData"
                ></menu-tree>
            </el-card>
            <el-card class="mt10" v-show="RoleFormState.distributeCardVisible">
                <template #header>
                    <div class="jxtech-card-title">
                        <span class="jxtech-page-table-header-flex-title">菜单权限（分配）</span>
                    </div>
                </template>
                <menu-tree
                    ref="MenuTreeDistributeRef"
                    :show-checkbox="true"
                    :is-custom-tree-data="true"
                    :custom-tree-data="RoleFormState.treeData"
                ></menu-tree>
            </el-card>
        </div>
    </div>
</template>